import request from '@/utils/request'

export const userAPI = {
  // 获取所有用户（带分页）
  getAllUsers: (page = 1, size = 10, search = '') => {
    return request.get('/users', { params: { page, size, search } })
  },

  // 获取所有带角色的用户
  getUsersWithRoles: () => {
    return request.get('/users/roles')
  },

  // 根据用户名获取用户
  getUserByUsername: (username) => {
    return request.get(`/users/username/${encodeURIComponent(username)}`)
  },

  // 批量分配角色给用户
  assignRolesToUser: (userId, roleIds) => {
    return request.post('/users/roles', { userId, roleIds })
  },

  // 移除用户的所有角色
  removeAllRolesFromUser: (userId) => {
    return request.delete(`/users/${userId}/roles`)
  },

  // 创建用户
  createUser: (data) => {
    return request.post('/users', data)
  },

  // 更新用户
  updateUser: (data) => {
    return request.put('/users', data)
  },

  // 删除用户
  deleteUser: (id) => {
    return request.delete(`/users/${id}`)
  },

  // 用户注册（兼容 data 对象或分别传参）
  register: (dataOrUsername, password, phone, email) => {
    const payload = typeof dataOrUsername === 'object'
      ? dataOrUsername
      : { username: dataOrUsername, password, phone, email }
    return request.post('/auth/register', payload, { headers: { 'Content-Type': 'application/json' } })
  },

  // 用户登录（返回 accessToken）
  login: (dataOrUsername, password) => {
    const payload = typeof dataOrUsername === 'object'
      ? dataOrUsername
      : { username: dataOrUsername, password }
    return request.post('/auth/login', payload, { headers: { 'Content-Type': 'application/json' } })
  },

  // 根据用户ID获取角色
  getRolesByUserId: (userId) => {
    return request.get(`/roles/user/${userId}`)
  },

  // 用户登出
  logout: (accessToken) => {
    return request.post('/auth/logout', {}, { headers: { 'Authorization': `Bearer ${accessToken}` } })
  },

  // 获取当前用户信息（由网关注入X-User-Id，仍需携带accessToken）
  getUserInfo: (accessToken) => {
    return request.get('/auth/info', { headers: { 'Authorization': `Bearer ${accessToken}` } })
  }
}